/**
 * SpringMVC restful 风格
 * 用户控制器，控制关于线下支付的一些业务逻辑操作
 * @author WangXinLei
 * @date 2014-11-18
 */
package com.chnbst.bstyun.controller.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.Pager;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.eos.CreateNum;
import com.chnbst.bstyun.eos.Eos;
import com.chnbst.bstyun.model.pojo.Cashflow;
import com.chnbst.bstyun.model.pojo.Deal;
import com.chnbst.bstyun.model.pojo.Goods;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.vo.OrderVo;
import com.chnbst.bstyun.service.CashflowService;
import com.chnbst.bstyun.service.DealService;
import com.chnbst.bstyun.service.GoodsService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.UserService;

/**
 * 控制器注解 请求映射注解
 * controller 代表类是控制器
 * restcontroller 代表类是控制器， 所有的方法 都是ajax方法
 * @author zhangq
 *
 */
@Controller
@RequestMapping("/sysAdmin")
public class OrderAdminController {
	//每页显示的用户数
	private int pageSize = 10;
	//用户列表页码
	private int currPage = 1;
	/**
	 * 注入 业务逻辑层
	 */
	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired
	private GoodsService goodsService;
	@Autowired 
	private CreateNum createNum;
	@Autowired
	private CashflowService cashflowService;
	@Autowired
	private DealService dealService;
	@Autowired
	private Eos eos;
	
	/**
	 * @return 订单列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/order/orderList",method=RequestMethod.GET)
	public ModelAndView orderList()throws Exception{
		return new ModelAndView("admin/financeManager/orderManager");
	}
	
	/**
	 * Ajax 分页查询订单列表list 
	 * @return 订单列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/order/orderList/search",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> orderList(String page,String last,HttpServletRequest request)throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		
		String goodsName = request.getParameter("gName");
		String orderState = request.getParameter("orderState");
		String isDredge = request.getParameter("isDredge");
		
		if(SignUtil.isNotEmpty(page)) {
			currPage = Integer.valueOf(page);
		}
		if(SignUtil.isNotEmpty(last)) {
			pageSize = Integer.valueOf(last);
		}
		
		map.put("goodsName", goodsName);
		map.put("orderState", orderState);
		map.put("isDredge", isDredge);
		
		int totalRows = orderService.selectOrderCount(map);
		int pageCount = Pager.getPageCount(totalRows, pageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, pageSize);
		map.put("start", start);
		map.put("pageSize", pageSize);
		map.put("sortField", "order_id");
		map.put("sortOrder", "desc");
		
		List<OrderVo> orderList = orderService.selectAllOrders(map);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("page", currPage);
		resultMap.put("pageCount", pageCount);
		resultMap.put("totalRows", totalRows);
		resultMap.put("orderList", orderList);
		
		return resultMap;
	}

	/**
	 * 根据order_id单条数据的详细信息 
	 * @return 订单列表详情页面
	 * @throws Exception
	 */
	@RequestMapping(value="/order/orderDetail/{orderId}",method=RequestMethod.GET)
	public ModelAndView orderDetail(@PathVariable Integer orderId)throws Exception{
		
		ModelAndView mav = new ModelAndView();
		OrderVo orderInfo = orderService.selectOrderDetailByOrderId(orderId);
		mav.addObject("orderInfo", orderInfo);
		mav.setViewName("admin/financeManager/orderDetail");
		return mav;
	}
	
	/**
	 * 根据ID和按钮id修改订单列表的状态 
	 * @return true 或者false
	 * @throws Exception
	 */
	@RequestMapping(value="/operate/order/updateOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateOrder(HttpServletRequest request,Integer orderId) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		OrderVo order = orderService.selectOrderDetailByOrderId(orderId);
		boolean isSuccess = false;
		
		Goods goods = goodsService.selectByGoodsId(order.getGoodsId());
		if(!"0".equals(goods.getGoodsRalateGoods())){
			map.put("message", "该商品已关联其他商品，不能退单！！");
		}else if(order.getBuyType() == 1||order.getBuyType() == 2){
			map.put("message", "该用户已升级续费，不能退单！！");
		}else{
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("orderState", 1);
			map1.put("userId", order.getUserId());
			List<Order> list = orderService.selectOrdersByMap(map1);
			if(list.size() < 2) {
				order.setOrderState(2);
				//修改订单状态
				boolean a = orderService.updateOrderByOrderId(order);
				
				User userInfo = userService.selectUserInfoByUserId(order.getUserId());
				User baseUser = userService.selectUserInfoByUserId(order.getParentId());
				baseUser.setAccountMoney(baseUser.getAccountMoney()+order.getPayMoney());
				//该余额冻结，目前还没有冻结功能
				baseUser.setInvoiceMoney(baseUser.getInvoiceMoney()-order.getPayMoney());
				String domain = userInfo.getCompanyDomainName();
				
				//修改user表中的账户余额
				boolean b = userService.updateAccountMoneyByUserId(baseUser);
				
				//新增现金收支明细数据
				Cashflow cashflow = new Cashflow();
				cashflow.setCashflowNum(createNum.createCashflowNum("2"));
				cashflow.setUserId(order.getParentId());
				cashflow.setOrderId(order.getOrderId());
				cashflow.setDealType(4);
				cashflow.setCreateTime(new Date());
				cashflow.setDisburseMoney(0.00);
				cashflow.setIncomeMoney(order.getPayMoney());
				cashflow.setThenAccount(baseUser.getAccountMoney());
				//支付方式没有确定
				cashflow.setPayWayId(2);
				cashflow.setIsCancel(1);
				
				boolean c = cashflowService.insertCashflow(cashflow);
				
				String dealName = order.getGoodsName();
				Deal deal = new Deal();
				deal.setDealDate(new Date());
				deal.setDealName(dealName+" -- 退款");
				deal.setDealNum(order.getOrderNum());
				deal.setDealState("4");
				deal.setDisburseMoney(0.00);
				deal.setIncomeMoney(order.getPayMoney());
				deal.setPayWayId(2);
				deal.setUserId(order.getUserId());
				deal.setParentId(order.getParentId());
				deal.setIsCancel(1);
				boolean d = dealService.insertDeal(deal);
				
				//普元同步退单
				eos.chargeBack(domain,order.getGoodsName(),order.getUserId(),1);
				
				isSuccess = a && b && c && d; 
				if(isSuccess){
					map.put("message", "退单成功！！");
				}else{
					map.put("message", "退单失败！！");
				}
			}else {
				map.put("message", "该账号已买过多个商品，不能退单！！");
			}
		}
		map.put("isSuccess", isSuccess);
		return map;
	}
}
